package com.douwong.student.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.douwong.student.R;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.ClassBaseActivity;
import com.douwong.student.contant.Config;
import com.douwong.student.db.AnswerRecordDBService;
import com.douwong.student.enums.E_CommandType;
import com.douwong.student.enums.E_Destination;
import com.douwong.student.factory.ThreadFactory;
import com.douwong.student.fragment.QuestionAnswerChoiceFragment;
import com.douwong.student.fragment.QuestionAnswerJudgeFragment;
import com.douwong.student.fragment.QuestionAnswerMultiChoiceFragment;
import com.douwong.student.interfaces.QuestionAnswerInteractInterface;
import com.douwong.student.model.AnswerRecord;
import com.douwong.student.model.AnswerRecordType;
import com.douwong.student.model.QaTopic;
import com.douwong.student.popuwindow.RightPopuwindow;
import com.douwong.student.socket.LTPServer;
import com.douwong.student.utils.CommonPlaneCommit;
import com.douwong.student.utils.DateTools;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.FtpUtils;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.ScreenUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;

import java.io.File;
import java.util.List;
import java.util.Random;

/**
 * @autor yichao
 * @time 2017/4/813:43
 * @des 问道互动
 */
public class QuestionAnswerActivity extends ClassBaseActivity {
    private static final String TAG = "QuestionAnswerActivity";
    public static boolean isShown = false;
    private TextView mTextTitlePic, mTextProess;
    private RelativeLayout mRlRootView;
    private ImageButton mImageButtonSubmit;
    private ImageView mImagePeople, mImagePlane;
  //  private LinearLayout mLlUpdata;
    private final int FTP_DOWN_LOADING = 220;
    private final int FTP_DOWN_SUCCESS = 221;
    private final int FTP_DOWN_FAIL = 222;
    private QuestionAnswerInteractInterface mAnswerInteractInterface;
    private Bitmap mBitmap;
    private boolean isCommit = false;
    private int[] planes = {R.mipmap.plane_1, R.mipmap.plane_2, R.mipmap.plane_3};
    private CommonPlaneCommit mPlaneCommit;
    private List<String> mAnswerInfo;
    private File mFile;
    private QaTopic mDeserialize;
    private AnswerRecordDBService mAnswerRecordDBService;
    private RightPopuwindow mErrPopuwindow;
    private RightPopuwindow mRightPopuwindow;
    private RightPopuwindow mErrPopuwindow1;

    @Override
    public void initView() {
        setContentView(R.layout.question_answer_interact_activity);
        mRlRootView = (RelativeLayout) findViewById(R.id.rl_root);
        mImageButtonSubmit = (ImageButton) findViewById(R.id.ib_submitButton_quizzes);
        mImagePeople = (ImageView) findViewById(R.id.iv_people);
        mImagePlane = (ImageView) findViewById(R.id.iv_plane_quizzes);
        mTextTitlePic = (TextView) findViewById(R.id.tv_Title_pic);
     //   mLlUpdata = (LinearLayout) this.findViewById(R.id.upload_ll);
        mTextProess = (TextView) findViewById(R.id.progress_text);

    }

    @Override
    protected void initData() {
        super.initData();
        isCommit = false;
        isShown = true;
        mPlaneCommit = new CommonPlaneCommit(this, mImagePlane, ScreenUtils.getScreenWidth(), ScreenUtils.getScreenWidth());
        registerReceiver(mReceiver, mFilter);


    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mImageButtonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提交答案
                if (!BaseApplication.isTeaching) {
                    ToastUtils.makeText(QuestionAnswerActivity.this, "教师不在线");
                    return;
                }
                mImageButtonSubmit.setSelected(true);
                mImageButtonSubmit.setClickable(false);

                isCommit = true;
                mAnswerInfo = mAnswerInteractInterface.getAnswerInfo();
                mAnswerInteractInterface.setCommitStatue();
                LTPServer.createInstance(QuestionAnswerActivity.this).sendMsg(mAnswerInfo, E_CommandType.qaSubmitAnswer, E_Destination.teacher, new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});

                planeColor();
            }
        });

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FTP_DOWN_LOADING:
                    long proess = (long) msg.obj;
                    mTextProess.setText(proess + "%");
                    break;
                case FTP_DOWN_SUCCESS:
                  //  mLlUpdata.setVisibility(View.INVISIBLE);
                    mRlRootView.setVisibility(View.VISIBLE);
                    mFile = (File) msg.obj;
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(mFile.getAbsolutePath(), opts);
                    opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
                    opts.inSampleSize = calculateInSampleSize(opts, 80, 80);
                    opts.inJustDecodeBounds = false;
                    mBitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath(), opts);
                    mAnswerInteractInterface.setImageView(mFile, mBitmap);
                    break;
                case FTP_DOWN_FAIL:
                 //   mLlUpdata.setVisibility(View.INVISIBLE);
                    break;
            }
        }
    };
    IntentFilter mFilter = new IntentFilter() {

        {
            addAction(Config.QUESTION_ANSWER_SEND);
            addAction(Config.QUESTION_ANSWER_PUBLICANSWER);
            addAction(Config.FINISH_QUESTION_ANSWER);
            addAction(Config.TEACHER_LEAVE_CLASS);
            addAction(Config.LOGIN_CLASS_FAILURE);
            addAction(Config.QUESTION_ANSWER_FILE_DOWN_FAILURE);
            addAction(Config.QUESTION_ANSWER_FILE_DOWN_SUCCESS);


        }

    };
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Config.QUESTION_ANSWER_SEND:
                    String stringExtra = intent.getStringExtra(Config.INTENT_DATA);
                    mDeserialize = JsonUtils.deserialize(stringExtra, QaTopic.class);
                    if (mDeserialize != null) {
                        setValue(mDeserialize);
                        final String imageUrl = mDeserialize.getImageUrl();
                        if (imageUrl != null && imageUrl.length() != 0) {
                            //下载图片
                          //  downFilePic(imageUrl);
                        } else {
                          //  logcatI((mLlUpdata==null)+"");
                        //    mLlUpdata.setVisibility(View.INVISIBLE);
                            mRlRootView.setVisibility(View.VISIBLE);

                        }
                    } else {
                        ToastUtils.makeText(QuestionAnswerActivity.this, "接受互动问答数据失败");
                        finish();
                    }
                    break;
                case Config.QUESTION_ANSWER_FILE_DOWN_FAILURE:
                    //附件下载失败
                    ToastUtils.makeText(QuestionAnswerActivity.this,"问答互动附件下载失败");

                    break;
                case Config.QUESTION_ANSWER_FILE_DOWN_SUCCESS:
                    //附件下载成功
                    ToastUtils.makeText(QuestionAnswerActivity.this,"问答互动附件下载成功");
                    String filePath = intent.getStringExtra(Config.INTENT_DATA);
                    if (filePath!=null && !filePath.equals("")){
                    mFile=new File(filePath);
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(mFile.getAbsolutePath(), opts);
                    opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
                    opts.inSampleSize = calculateInSampleSize(opts, 80, 80);
                    opts.inJustDecodeBounds = false;
                    mBitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath(), opts);
                    mAnswerInteractInterface.setImageView(mFile, mBitmap);

                    }


                    break;
                case Config.QUESTION_ANSWER_PUBLICANSWER:
                    //公布互动问答答案
                    //公布答案
                    String extra = intent.getStringExtra(Config.INTENT_DATA);
                    LogUtils.i(TAG, "互动问答的答案" + extra);
                    StringBuilder stringBuilder = new StringBuilder();
                    if (extra != null) {
                        JSONArray jsonArray = JSONArray.parseArray(extra);
                        if (jsonArray != null) {
                            for (Object str : jsonArray) {
                                LogUtils.i(TAG, (String) str);
                                stringBuilder.append((String) str);
                            }
                        }
                    }
                    String onlineAnswer = stringBuilder.toString();
                    if (!isCommit) {
                        //错
                        mErrPopuwindow = new RightPopuwindow(QuestionAnswerActivity.this, false);
                        mErrPopuwindow.showAtLocation(mRlRootView, Gravity.CENTER, 0, 0);
                        savaToDbServer(mDeserialize,"",stringBuilder);
                        return;
                    }

                    String old = "";
                    for (String oldAnswer : mAnswerInfo) {
                        old += oldAnswer;
                    }
                    if (old.equalsIgnoreCase(onlineAnswer)) {
                        //dui
                        mRightPopuwindow = new RightPopuwindow(QuestionAnswerActivity.this, true);
                        mRightPopuwindow.showAtLocation(mRlRootView, Gravity.CENTER, 0, 0);
                        LogUtils.i(TAG, "该题做对了");
                    } else {
                        //cuo
                        mErrPopuwindow1 = new RightPopuwindow(QuestionAnswerActivity.this, false);
                        mErrPopuwindow1.showAtLocation(mRlRootView, Gravity.CENTER, 0, 0);
                        LogUtils.i(TAG, "该题做错了");
                    }
                    savaToDbServer(mDeserialize,old,stringBuilder);

                    //保存数据到数据库
                    /**    intent.putExtra("FilePath", record.getFilePath());
                     intent.putExtra("TitleName", record.getTitleName());
                     intent.putExtra("OptionStr", record.getOptionStr());
                     intent.putExtra("StudentAnswer", record.getStudentAnswer());
                     intent.putExtra("TrueAnswer", record.getTrueAnswer());
                     String trueAnswer = record.getTrueAnswer();
                     intent.putExtra("AwardCount", record.getAwardCount());
                     intent.putExtra("Type", record.getType().getTip());
                     intent.putExtra("CorrectRate", record.getCorrectRate());*/
                    break;
                case Config.FINISH_QUESTION_ANSWER:
                case Config.TEACHER_LEAVE_CLASS:
                case Config.LOGIN_CLASS_FAILURE:
                    finish();
                    break;

            }
        }
    };

    /**
     * 保存数据到数据库
     * @param deserialize
     * @param studnetAnswer
     * @param trueAnswer
     */
    private void savaToDbServer(QaTopic deserialize, String studnetAnswer, StringBuilder trueAnswer) {
        AnswerRecord answerRecord = new AnswerRecord();
        if (mFile!=null){
            answerRecord.setFilePath(mFile.getAbsolutePath());
        }
        answerRecord.setTitleName(deserialize.getBody());
        answerRecord.setCreateTime(DateTools.getLineDate());
        answerRecord.setAwardCount(0);
        answerRecord.setStudentAnswer(studnetAnswer);
        answerRecord.setTrueAnswer(trueAnswer.toString());
        answerRecord.setCorrectRate("");
        switch (deserialize.getSubjectType()) {
            case single:
                answerRecord.setType(AnswerRecordType.Single);
                break;
            case multiple:
                answerRecord.setType(AnswerRecordType.Multiple);
                break;

            case judgment:
                answerRecord.setType(AnswerRecordType.Judge);
                break;
        }


        //答案
        String options="";
        if (deserialize.getOptions()!=null&&deserialize.getOptions().size()>0){
            for (int i = 0; i < deserialize.getOptions().size(); i++) {
                if (i==deserialize.getOptions().size()-1){
                    options+=deserialize.getOptions().get(i);
                }else {
                    options+=deserialize.getOptions().get(i)+"###";
                }


            }
        }
        answerRecord.setOptionStr(options);
        if (mAnswerRecordDBService == null) {
            mAnswerRecordDBService = new AnswerRecordDBService(QuestionAnswerActivity.this);
        }
        int    databaseId = mAnswerRecordDBService.addAnswerRecord(answerRecord, BaseApplication.sUserBean.getUserbean().getEuNumber());
        logcatI("保存问答互动 插入数据库 databaseId"+databaseId);

    }

    /**
     * 飞机随机出现颜色
     */
    public void planeColor() {
        Random random = new Random();
        int pick = random.nextInt(planes.length);
        mImagePlane.setBackgroundResource(planes[pick]);
        mImagePlane.setVisibility(View.VISIBLE);// 执行飞机动画
        mImagePlane.startAnimation(mPlaneCommit.getAnimationSet());
    }

    /**
     * 下载图片
     *
     * @param imageUrl
     */
    private void downFilePic(final String imageUrl) {
        ThreadFactory.getDownLoadPool().execute(new Runnable() {
            @Override
            public void run() {
                int index = imageUrl.lastIndexOf("/");
                String imageName = imageUrl.substring(index + 1, imageUrl.length());
                FtpUtils ftp = new FtpUtils();
                try {

                    ftp.downloadSingleFile(imageUrl, FileUtils.IMAGE_DIR, imageName, new FtpUtils.DownLoadProgressListener() {
                        @Override
                        public void onDownLoadProgress(String currentStep, long downProcess, File file) {
                            Message message = mHandler.obtainMessage();
                            switch (currentStep) {
                                case Config.FTP_DOWN_FAIL:
                                    ToastUtils.makeText(UIUtils.getContext(), "互动问答下载图片失败");
                                    message.what = FTP_DOWN_FAIL;
                                    mHandler.sendMessage(message);
                                    break;
                                case Config.FTP_DOWN_LOADING:
                                    message.what = FTP_DOWN_LOADING;
                                    LogUtils.i(TAG, "下载进度" + downProcess);
                                    message.obj = downProcess;
                                    mHandler.sendMessage(message);
                                    break;
                                case Config.FTP_DOWN_SUCCESS:
                                    message.what = FTP_DOWN_SUCCESS;
                                    message.obj = file;
                                    mHandler.sendMessage(message);
                                    break;
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                 //   mLlUpdata.setVisibility(View.INVISIBLE);
                    ToastUtils.makeText(QuestionAnswerActivity.this, "互动问答下载图片失败");
                }
            }
        });

    }

    /**
     * 设置数据
     *
     * @param qaTopic
     */
    private void setValue(QaTopic qaTopic) {
        switch (qaTopic.getSubjectType()) {
            case single:
                mTextTitlePic.setBackgroundResource(R.mipmap.radiobuttonlistpic);
                QuestionAnswerChoiceFragment questionAnswerChoiceFragment = new QuestionAnswerChoiceFragment(this, qaTopic);
                mAnswerInteractInterface = questionAnswerChoiceFragment;
                commitFragmet(questionAnswerChoiceFragment);
                break;
            case multiple:
                mTextTitlePic.setBackgroundResource(R.mipmap.multiple_choice_question_pic);
                QuestionAnswerMultiChoiceFragment multiChoiceFragment = new QuestionAnswerMultiChoiceFragment(this, qaTopic);
                mAnswerInteractInterface = multiChoiceFragment;
                commitFragmet(multiChoiceFragment);
                break;
            case judgment:
                mTextTitlePic.setBackgroundResource(R.mipmap.judgment_questions_pic);
                QuestionAnswerJudgeFragment questionAnswerJudgeFragment = new QuestionAnswerJudgeFragment(this, qaTopic);
                mAnswerInteractInterface = questionAnswerJudgeFragment;
                commitFragmet(questionAnswerJudgeFragment);

                break;
        }
    }

    private void commitFragmet(Fragment fragment) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.framelayout, fragment);
        fragmentTransaction.commit();

    }


    public static void startActivity(Context context) {
        Intent intent = new Intent(context, QuestionAnswerActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isShown = false;
        isCommit = false;
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        if (mBitmap!=null&&!mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
            System.gc();
        }
        if (mRightPopuwindow!=null && mRightPopuwindow.isShowing()){
            mRightPopuwindow.dismiss();
        }
        if (mErrPopuwindow!=null && mErrPopuwindow.isShowing()){
            mErrPopuwindow.dismiss();
        }
        if (mErrPopuwindow1!=null && mErrPopuwindow1.isShowing()){
            mErrPopuwindow1.dismiss();
        }
    }

    /**
     * 计算缩放比例
     *
     * @param op
     * @param reqWidth
     * @param reqheight
     * @return
     */
    public int calculateInSampleSize(BitmapFactory.Options op, int reqWidth,
                                     int reqheight) {
        int originalWidth = op.outWidth;
        int originalHeight = op.outHeight;
        int inSampleSize = 1;
        if (originalWidth > reqWidth || originalHeight > reqheight) {
            int halfWidth = originalWidth / 2;
            int halfHeight = originalHeight / 2;
            while ((halfWidth / inSampleSize > reqWidth)
                    && (halfHeight / inSampleSize > reqheight)) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}
